
from feature import Feature, FeatureParser, registerFeatureParserClass

class FastaFeature(Feature):
    
    def getDetails(self):
        self.seq = self.content.strip()
        return self

class FastaFeatureParser(FeatureParser):
    '''
    Parser for lines in .fa file.
    '''
    def __init__(self):
        self.chr = None
        self.pos = 0
        self.lastIndexContext = None

    def parse(self, line):
        if line == None or line.startswith("#"): return None
        if line.startswith(">"):
            self.chr = line.strip()[1:]
            self.pos = 1
            self.lastIndexContext = "%s %ld" % (self.chr, self.pos)
            return None
        seq = line.strip()
        feature = FastaFeature(self.chr, self.pos, self.pos + len(seq) - 1, line)
        self.lastIndexContext = self.getIndexContext()
        self.pos += len(seq)
        return feature

    def getLastIndexContext(self):
        '''Return the context in which the most recently parsed feature was parsed.'''
        return self.lastIndexContext
    
    def getIndexContext(self):
        '''Return the context in which the next feature will be parsed.'''
        return "%s %ld" % (self.chr, self.pos)
    
    def setIndexContext(self, context):
        '''Parse the next feature in the specified context.'''
        fields = context.split(" ")
        self.chr = fields[0]
        self.pos = long(fields[1])
    
    def getMaxFeatureSize(self):
        return 100

registerFeatureParserClass("fa", FastaFeatureParser)

